 //
//  ServiceControllerView.m
//  DMGME
//
//  Created by ihope99 on 15/9/6.
//  Copyright (c) 2015年 GYP. All rights reserved.
//

#import "ServiceControllerView.h"
#import <BaiduMapAPI/BMapKit.h>
#import <BaiduMapAPI/BMKGeocodeSearchOption.h>
#import <BaiduMapAPI/BMKGeocodeSearch.h>
#import "mapVTool.h"

@interface ServiceControllerView ()<UITableViewDataSource,UITableViewDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate,BMKGeoCodeSearchDelegate,UIScrollViewDelegate,UITextFieldDelegate>

@end

@implementation ServiceControllerView
{
    UIView *mapViw;
    UITableView *tableview;
    mapVTool *_mapView;  //创建地图
    BMKGeoCodeSearch* _geocodesearch;// 地理位置检索
    BMKPoiSearch *_poiSearch; // poi 检索
    
    NSString *_address; // 地址
    NSString *_addressDetail; // 地址详情
    NSMutableArray *array ;// 存放周边检索地址
    NSArray *array1 ;// 存放收索附近地点
    BMKPoiInfo *info; //检索信息
    UITextField *searchTextF;
    NSString *onLongClickResultAdress;
    
    NSString *onLongClicklongitude;
    NSString *onLongClicklatitude;
    BMKPointAnnotation* animatedAnnotation;
    
    BOOL isSeacher;
    BOOL isOnLongClick;
}
-(NSMutableDictionary *)dictAddess{
    if (_dictAddress == nil) {
        _dictAddress = [NSMutableDictionary dictionary];
    }
    return _dictAddress;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self;// 不用时，置nil
    _mapView.showsUserLocation = NO;
   
    //移除标注
    for ( BMKPointAnnotation *ani in _mapView.annotations) {
        [_mapView removeAnnotation:ani];
    }
    //    //    发起反向地理编码检索
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){[[_mapView.addressDic objectForKey:@"latitude"]  floatValue],[[_mapView.addressDic objectForKey:@"longitude"]  floatValue]};
    
//    selected
    [_mapView removeAnnotation:animatedAnnotation];
    animatedAnnotation = [[BMKPointAnnotation alloc]init];
    animatedAnnotation.coordinate = pt;
    animatedAnnotation.title = @"设为店铺地址";
    [_mapView addAnnotation:animatedAnnotation];
    [_mapView selectAnnotation:animatedAnnotation animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _poiSearch.delegate = nil;
    _geocodesearch.delegate = nil;
}
- (void)adressPoiStr:(void(^)(NSString *adressLng,NSString *adressLat,NSString *adressStr))blok{
//    ad
    self.AdressPoiStr = blok;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    isSeacher = YES;
    isOnLongClick = NO;

    // Do any additional setup after loading the view.
    [self creatMapView];
    [self creatAdressView];
    [self AddLeftImageBtn:[UIImage imageNamed:@"fanhui_03 2"]target:self action:@selector(GoBack)];
    [self setTitle:@"上传店铺坐标"];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [searchTextF resignFirstResponder];
    isSeacher = NO;
    [self textChange];
    return YES;
}
- (void)creatMapView{
    
    _mapView = [mapVTool showInRect:CGRectMake(0, 0, KWidth, 310)];
    [_mapView setMapCenterToScreenPt:CGPointMake(self.view.bounds.size.width *0.5,_mapView.bounds.size.height*0.5)];
    
    // 地图 比例尺级别，在手机上当前可使用的级别为3-19级
    _mapView.delegate = self;
    _mapView.zoomLevel = 18;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    [self.view addSubview:_mapView];
    
    
    //初始化检索对象
    _poiSearch =[[BMKPoiSearch alloc]init];
    _poiSearch.delegate = self;
    

    
    
    // 创建搜索框
    UIView *textFBackView = [[UIView alloc] init];
    textFBackView.frame = CGRectMake(12, 12, KWidth - 24, 40);
    textFBackView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *searcherImage = [[UIImageView alloc] init];
    searcherImage.frame = CGRectMake(12, 12, 16, 16);
    [searcherImage setImage:[UIImage imageNamed:@"SearchButton"]];
    [textFBackView addSubview:searcherImage];
    
    searchTextF = [[UITextField alloc] init];
    searchTextF.frame = CGRectMake(40 , 0, WIDTH(textFBackView) - 40, 40);
    searchTextF.backgroundColor = [UIColor clearColor];
    searchTextF.delegate = self;
    searchTextF.inputAccessoryView = [self GetInputAccessoryView];
    searchTextF.placeholder = @"查找小区/学校/大厦等";
    
    [searchTextF addTarget:self action:@selector(textChange) forControlEvents:UIControlEventEditingChanged];

    [textFBackView addSubview:searchTextF];
    [self.view addSubview:textFBackView];
}
- (void)textChange
{
    if (searchTextF.text.length>=1) {

        //发起检索
        BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
        option.pageIndex = 0;
        option.pageCapacity = 50;
        option.location = CLLocationCoordinate2DMake([[_mapView.addressDic objectForKey:@"latitude"] floatValue], [[_mapView.addressDic objectForKey:@"longitude"] floatValue]);
        option.keyword =searchTextF.text;
    
        option.sortType =BMK_POI_SORT_BY_COMPOSITE;
        BOOL flag = [_poiSearch poiSearchNearBy:option];
        if(flag)
        {
//            NSLog(@"周边检索发送成功");
        }
        else
        {
//            NSLog(@"周边检索发送失败");
        }
    }
}


- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error
{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        _mapView.address = poiResultList.poiInfoList;
        [tableview reloadData];

    
    }
    else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
//        NSLog(@"起始点有歧义");
        
    } else {
//        NSLog(@"抱歉，未找到结果");
//        NSLog(@"%u",error);
        if (isSeacher == NO) {
            [self showMsg:@"没有收索到相关结果 请您选择用地图标注您所在的位置"];
            isSeacher = YES;
        }
    }
}

// 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //普通annotation
   
        NSString *AnnotationViewID = @"renameMark";
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            // 设置颜色
            annotationView.pinColor = BMKPinAnnotationColorPurple;
            // 从天上掉下效果
            annotationView.animatesDrop = YES;
            // 设置可拖拽
            annotationView.draggable = YES;
            annotationView.image = [UIImage imageNamed:@"30"];
//            _mapView.show
            annotationView.paopaoView.backgroundColor = [UIColor blueColor];

        }
        return annotationView;
    }
//- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
//}

// 当点击annotation view弹出的泡泡时，调用此接口
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view;
{
//    NSLog(@"paopaoclick");
    onLongClicklongitude = [NSString stringWithFormat:@"%f",view.annotation.coordinate.longitude];
    onLongClicklatitude = [NSString stringWithFormat:@"%f",view.annotation.coordinate.latitude];
   
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = view.annotation.coordinate;
    
    
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
    
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
        isOnLongClick = YES;
        [self showMsg:@"反geo检索发送成功~~~~"];
//        NSLog(@"反geo检索发送成功~~~~");
    }
    else
    {
        isOnLongClick = NO;

        [self showMsg:@"反geo检索发送失败~~~~"];

//        NSLog(@"反geo检索发送失败~~~~");
    }
    
//    [self.navigationController popViewControllerAnimated:YES];
}


/**
 *长按地图时会回调此接口
 *@param mapview 地图View
 *@param coordinate 返回长按事件坐标点的经纬度
 */
- (void)mapview:(BMKMapView *)mapView onLongClick:(CLLocationCoordinate2D)coordinate{
    
    [_mapView removeAnnotation:animatedAnnotation];
    animatedAnnotation = [[BMKPointAnnotation alloc]init];
    animatedAnnotation.coordinate = coordinate;
    animatedAnnotation.title = @"设为店铺地址";
   [_mapView addAnnotation:animatedAnnotation];

}

#pragma mark - 百度地图代理方法
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    BMKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center= centerCoordinate;
    
    NSString *latitude = [NSString stringWithFormat:@"%f",centerCoordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f",centerCoordinate.longitude];
    
    [self.dictAddess setValue:latitude forKey:@"latitude"];
    [self.dictAddess setValue:longitude forKey:@"longitude"];
    
    [_mapView removeAnnotation:animatedAnnotation];
    animatedAnnotation = [[BMKPointAnnotation alloc]init];
    animatedAnnotation.coordinate = centerCoordinate;
    animatedAnnotation.title = @"设为店铺地址";
    [_mapView addAnnotation:animatedAnnotation];
    [_mapView selectAnnotation:animatedAnnotation animated:YES];

  
    //    发起反向地理编码检索
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){[latitude floatValue],[longitude floatValue]};
    [_mapView.addressDic removeAllObjects];
    
    [_mapView.addressDic setValue:latitude forKey:@"latitude"];
    [_mapView.addressDic setValue:longitude forKey:@"longitude"];
    
    NSLog(@"regionDidChangeAnimated;%@, %@", latitude, longitude);
    
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
    
    
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
//        NSLog(@"反geo检索发送成功");
    }
    else
    {
//        NSLog(@"反geo检索发送失败");
    }
}
//接收反向地理编码结果
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
//        NSLog(@"在此处理正常结果");
       //长点击 接收反地理编码
        if (isOnLongClick == YES) {
            onLongClickResultAdress = result.address;
            self.AdressPoiStr(onLongClicklongitude,onLongClicklatitude,onLongClickResultAdress);
            isOnLongClick = NO;
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        //移动地图 接收反地理编码
        else{
        
        //初始化检索对象
        _poiSearch =[[BMKPoiSearch alloc]init];
        _poiSearch.delegate = self;
        //发起检索
        BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
        option.pageIndex = 1;
        option.pageCapacity = 20;
        option.location = CLLocationCoordinate2DMake([[_mapView.addressDic objectForKey:@"latitude"] floatValue], [[_mapView.addressDic objectForKey:@"longitude"] floatValue]);

        _mapView.address = result.poiList;
        [tableview reloadData];
        }
        
    }
    else {
        
//        NSLog(@"抱歉，未找到结果");
    }
}
- (void)creatAdressView{
    tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, HEIGHT(_mapView), KWidth, KHeight  - HEIGHT(_mapView)) style:UITableViewStylePlain];
    tableview.delegate = self;
    tableview.dataSource = self;
    tableview.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:tableview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _mapView.address.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId =@"cell1";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    info = _mapView.address[indexPath.row];
    cell.textLabel.text =info.name;
    cell.detailTextLabel.text = info.address;
    cell.detailTextLabel.textColor = [UIColor grayColor];

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    info = _mapView.address[indexPath.row];
    searchTextF.text = info.name;
     [[mapVTool sharedInstance]setCenterCoordinate:info.pt animated:YES];
}
//接收正向编码结果
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        
        [[mapVTool sharedInstance]setCenterCoordinate:result.location animated:YES];
        
    }
    else {
//        NSLog(@"抱歉，未找到结果");
    }
}


/*
 
 
 [[mapVTool sharedInstance]setCenterCoordinate:result.location animated:YES];
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
